<template>
    <div class="chart-wrapper">
        <BaseChart v-if="chartOption" ref="baseChartRef" height="100%" width="100%" :options="chartOption" />
        <div v-else class="loading-wrapper">
            <el-empty v-if="!loading" description="暂无数据"></el-empty>
            <div v-else class="loading">加载中...</div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import BaseChart from './BaseChart.vue';
import { getReportApi } from '@/api/meter';
import { useCompanyStore } from '@/stores/company';
import dayjs from 'dayjs';
import { checkTimeRange } from '../../utils/date';


const props = defineProps({
    data: {
        type: Array,
        default: () => []
    },
    type: {
        type: String,
        default: 'month'
    },
    metric: {
        type: String,
        default: 'water'
    },
    year: {
        type: [String, Number],
        default: () => dayjs().format('YYYY')
    }
});

const companyStore = useCompanyStore();
const baseChartRef = ref(null);
const actualData = ref([]);
const loading = ref(false);

// 获取资源类型ID
const getResourceTypeId = (metric) => {
    switch (metric) {
        case 'water': return 1;  // 水表类型
        case 'electricity': return 2;  // 电表类型
        case 'gas': return 3;  // 气表类型
        default: return 1;  // 默认为水表
    }
};


// 根据图表类型生成时间配置
const generateTimeConfig = (type, year) => {
    let config = {
        start_time: dayjs(year).startOf('year').valueOf(),
        end_time: dayjs(year).endOf('year').add(1, 'day').startOf('day').valueOf(),
        interval: type
    }
    return checkTimeRange(config);
};
// 处理实际数据，使其与计划数据格式兼容
const processActualData = (data, type, selectedYear) => {
    if (!data || !Array.isArray(data)) return [];

    const targetYear = parseInt(selectedYear);

    return data.reduce((result, item) => {
        const startTimeStr = item.start_time; // 格式: "2024-12-05T00:00:00+08:00"
        const date = dayjs(startTimeStr);

        // 检查数据年份是否与选定年份匹配
        const dataYear = date.year();
        if (dataYear !== targetYear) {
            return result; // 跳过不匹配的年份数据
        }

        let formattedTimestamp = '';
        if (type === 'month') {
            formattedTimestamp = date.format('YYYY-MM-01');
        } else if (type === 'quarter') {
            formattedTimestamp = `${date.format('YYYY第')}${date.quarter()}季度`;
        } else if (type === 'year') {
            formattedTimestamp = date.format('YYYY');
        }

        // 双重验证：确保格式化后的时间戳也包含正确的年份
        if (type === 'year' && formattedTimestamp !== selectedYear.toString()) {
            return result;
        } else if ((type === 'month' || type === 'quarter') &&
            !formattedTimestamp.startsWith(selectedYear.toString())) {
            return result;
        }

        result.push({
            start_time: formattedTimestamp,
            usage: Number((Number(item.Value) || 0).toFixed(2)) // 保留两位小数
        });

        return result;
    }, []);
};

// 获取实际数据
const fetchActualData = async () => {
    if (!companyStore.currentCompany?.id) {
        console.error('未选择公司，无法获取实际数据');
        return;
    }

    try {
        loading.value = true;

        // 根据类型确定时间配置
        const timeConfig = generateTimeConfig(props.type, props.year);
        const params = {
            id: companyStore.currentCompany.id,
            start_time: timeConfig.start_time,
            end_time: timeConfig.end_time,
            interval: timeConfig.interval,
            type: getResourceTypeId(props.metric) // 根据当前选择的资源类型获取相应类型的数据
        };

        const response = await getReportApi(params);

        if (response && response.aggregated_data) {
            // 处理返回的数据，格式化为与计划数据相似的格式
            // 传入选定的年份用于过滤
            actualData.value = processActualData(response.aggregated_data, props.type, props.year);
        } else {
            actualData.value = [];
        }
    } catch (error) {
        console.error('获取实际数据失败', error);
        actualData.value = [];
    } finally {
        loading.value = false;
    }
};
// 根据类型和数据格式化X轴标签
const formatXAxisLabels = (data, type) => {
    return data.map(item => {
        const startTime = item.start_time;
        if (type === 'month') {
            // 将 YYYY-MM-01 格式化为 YYYY年MM月
            return startTime.replace(/(\d{4})-(\d{2})-\d{2}/, '$1年$2月');
        } else if (type === 'quarter') {
            // 已经是 YYYY第Q季度 格式
            return startTime;
        } else if (type === 'year') {
            // 将 YYYY 格式化为 YYYY年
            return `${startTime}年`;
        }
        return startTime;
    });
};

// 合并计划数据和实际数据的时间标签
const mergeTimestamps = computed(() => {
    const planTimestamps = props.data.map(item => item.start_time);

    if (actualData.value.length === 0) {
        return planTimestamps;
    }

    const actualTimestamps = actualData.value.map(item => item.start_time);

    // 合并并去重
    const allTimestamps = [...new Set([...planTimestamps, ...actualTimestamps])];

    // 排序
    return allTimestamps.sort((a, b) => a.localeCompare(b));
});

// 获取指定时间戳的计划数据值
const getPlanValue = (timestamp) => {
    const item = props.data.find(item => item.start_time === timestamp);
    return item ? Number(item.usage.toFixed(2)) : 0; // 将null改为0
};


// 获取指定时间戳的实际数据值
const getActualValue = (timestamp) => {
    const item = actualData.value.find(item => item.start_time === timestamp);
    return item ? Number(item.usage.toFixed(2)) : 0; // 将null改为0
};
// 获取度量类型的显示名称
const getMetricName = (metric) => {
    switch (metric) {
        case 'water': return '用水量';
        case 'electricity': return '用电量';
        case 'gas': return '用气量';
        default: return '用水量';
    }
};

// 获取度量类型的单位
const getMetricUnit = (metric) => {
    switch (metric) {
        case 'water': return 'm³';
        case 'electricity': return 'kWh';
        case 'gas': return 'm³';
        default: return 'm³';
    }
};

// 动态计算图表配置
const chartOption = computed(() => {
    if ((!props.data || props.data.length === 0) && actualData.value.length === 0) {
        return null;
    }

    const timestamps = mergeTimestamps.value;
    const xAxisData = formatXAxisLabels(timestamps.map(t => ({ start_time: t })), props.type);
    const planValues = timestamps.map(getPlanValue);
    const actualValues = timestamps.map(getActualValue);
    const metricName = getMetricName(props.metric);
    const metricUnit = getMetricUnit(props.metric);

    // 构建符合BaseChart要求的options对象
    const series = [
        {
            name: `计划${metricName}`,
            data: planValues,
            type: 'bar',
        }
    ];

    // 如果有实际数据，添加实际数据系列
    if (actualData.value && actualData.value.length > 0) {
        series.push({
            name: `实际${metricName}`,
            data: actualValues,
            type: 'bar',
        });
    }

    return {
        xAxisData: xAxisData,
        yAxisUnit: metricUnit,
        series: series,
        customColors: ['#409EFF', '#67C23A'],
        isStacked: false,
        legend: {
            show: series.length > 1,
            data: series.map(s => s.name)
        }
    };
});

// 当参数变化时重新获取数据
watch([() => props.type, () => props.metric, () => props.year], () => {
    fetchActualData();

    // 确保图表重新渲染
    if (baseChartRef.value && baseChartRef.value.updateChart) {
        // 使用 nextTick 确保状态更新后再更新图表
        nextTick(() => {
            baseChartRef.value.updateChart();
        });
    }
}, { deep: true });

// 当公司变化时重新获取数据
watch(() => companyStore.currentCompany, () => {
    fetchActualData();
});

// 组件挂载时获取数据
onMounted(() => {
    fetchActualData();
});

</script>

<style scoped>
.chart-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
}

.loading-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.loading {
    color: #909399;
}
</style>